from PySide2.QtWidgets import QWidget, QPushButton, QFileDialog, QVBoxLayout, QListWidget, QListView, QListWidgetItem
from PySide2.QtCore import QSize, Qt

import datetime
from pathlib import Path

from tool import util, storage, dbutil
from custom.VideoListWidget import VideoListWidget

VideoDirKey = "VideoDirKey"


class LocalVideo(QWidget):

    def __init__(self):
        super(LocalVideo, self).__init__()

        self.layout = QVBoxLayout(self)

        self.fileButton = QPushButton("选择文件夹")
        self.fileButton.clicked.connect(self.onClickFile)

        self.listWidget = VideoListWidget()
        self.layout.addWidget(self.fileButton)
        self.layout.addWidget(self.listWidget)

        self.videoDir = storage.getValue(VideoDirKey)
        self.showVideos()

    def onClickFile(self):
        self.videoDir = QFileDialog.getExistingDirectory(
            None, "选取文件夹", "")
        storage.store(VideoDirKey, self.videoDir)
        self.showVideos()
        
    def showVideos(self):
        if not self.videoDir:
            return
        filepaths = list(Path(self.videoDir).glob('*.mp4'))
        for filepath in filepaths:
            dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            path = str(filepath)
            shotname = filepath.stem
            dic = {
                "name": shotname,
                "title": shotname,
                "path": path,
                "vid": util.md5(path),
                "tags": util.participle_str(shotname),
                "platform": "local",
                "create_time": dt,
                "add_time": dt,
            }
            dbutil.insertVideo(dic)
        
        self.list, self.total = dbutil.fetchVideo(1, 10, 'local')
        self.listWidget.reloadData(self.list)
